﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Resources;
using System.Collections;
using System.Globalization;

namespace SolutionSorter.Core
{
    public static class EmbeddedAssemblyLoader
    {
        public static Assembly LoadAssemby(string assemblyName)
        {
            string[] resources = Assembly.GetExecutingAssembly().GetManifestResourceNames();
            foreach (string resource in resources)
            {
                string baseName = resource.Substring(0, resource.LastIndexOf('.'));
                ResourceManager resourceManager = new ResourceManager(baseName, Assembly.GetExecutingAssembly());
                ResourceSet resourceSet = resourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, true);
                IDictionaryEnumerator enumerator = resourceSet.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    object obj = enumerator.Value;
                    if (obj is byte[])
                    {
                        try
                        {
                            Assembly assembly = Assembly.Load((byte[])obj);
                            if (assemblyName == assembly.GetName().FullName) return assembly;
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                }
            }
            return null;
        }
    }
}
